package com.nand.blockdemo.ui;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lzy.okgo.model.HttpParams;
import com.nand.blockdemo.ItemOffsetDecoration;
import com.nand.blockdemo.Loader.GlideImageLoader;
import com.nand.blockdemo.R;
import com.nand.blockdemo.adapter.GridAdapter;
import com.nand.blockdemo.adapter.NewsAdapter;
import com.nand.blockdemo.bean.BannerBean;
import com.nand.blockdemo.bean.GridItem;
import com.nand.blockdemo.bean.ModuleBean;
import com.nand.blockdemo.bean.ModuleListBean;
import com.nand.blockdemo.bean.NewsListBean;
import com.nand.blockdemo.bean.VersionBean;
import com.nand.blockdemo.constant.URL;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.SpUtils;
import com.nand.module.function.bean.EqDatailBean;
import com.nand.module.function.ui.ClampingActivity;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.user.ui.UserInfoActivity;
import com.youth.banner.Banner;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

@Route(path = "/app/main")
public class MainActivity extends BaseActivity implements View.OnClickListener, OnButtonClickListener {

    private Banner banner;
    private NewsAdapter mainAdapter;
    private GridAdapter gridAdapter;
    private List<String> images = new ArrayList();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        TaskLocalDataSource dataSource = new TaskLocalDataSource(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        XPopup.setPrimaryColor(getResources().getColor(R.color.blue));
        //设置状态栏透明
        setStatusBar(R.color.transparent);
        //初始化layout中的控件
        RecyclerView homeRecyclerView = findViewById(R.id.recycler_home_view);
        homeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mainAdapter = new NewsAdapter(R.layout.item_news_layout);

        //添加顶部2个view  分别为轮播图、功能模块
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(initTopView());
        layout.addView(initTopView1());

        //添加新闻标题
        TextView textView = new TextView(this);
        textView.setText("资讯");
        textView.setPadding(20, 15, 0, 5);
        layout.addView(textView);

        mainAdapter.addHeaderView(layout);
        homeRecyclerView.setAdapter(mainAdapter);

        findViewById(R.id.im_login).setOnClickListener(this);

        //item点击进入新闻详情
        mainAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<NewsListBean.NewsLits> lists = adapter.getData();
                String newsId = lists.get(position).getNewsId();
                ARouter.getInstance().build("/news/details").withString("newsId", newsId).navigation();
//                ARouter.getInstance().build("/function/eqair/list").navigation();
            }
        });
    }


    /**
     * 初始化轮播图view
     *
     * @return
     */
    private View initTopView() {
        RelativeLayout view = (RelativeLayout) getLayoutInflater().inflate(R.layout.item_banner_layout, null);
        banner = view.findViewById(R.id.banner_view);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        banner.setImages(images);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        return view;
    }


    /**
     * 初始化功能模块view
     *
     * @return
     */
    private View initTopView1() {
        RelativeLayout view = (RelativeLayout) getLayoutInflater().inflate(R.layout.item_home_function_layout, null);
        RecyclerView recyclerView = view.findViewById(R.id.rv_modular);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        ItemOffsetDecoration itemOffsetDecoration = new ItemOffsetDecoration(this, R.dimen.dp_5);
        recyclerView.addItemDecoration(itemOffsetDecoration);
        gridAdapter = new GridAdapter(this);
        recyclerView.setAdapter(gridAdapter);
        return view;
    }


    @Override
    protected void initData() {
        getBannerData();
        getModuleData();
        getNewsData();
        mVersionUpdate();
    }

    /**
     * get轮播图数据
     */
    private void getBannerData() {
        OkGoUtils.getInstance().post(this, URL.BANNER_IMAGE_URL, null, 0, false, mCallback);
    }

    /**
     * get新闻数据
     */
    private void getNewsData() {

        HttpParams paramsPost = new HttpParams();
        paramsPost.put("current", "1");
        paramsPost.put("size", "10");
        OkGoUtils.getInstance().post(this, URL.NEWS_LIST_URL, paramsPost, 1, false, mCallback);
    }

    /**
     * get功能模块权限展示数据
     */
    private void getModuleData() {
        OkGoUtils.getInstance().post(this, URL.MODULE_POWER_URL, null, 2, false, mCallback);
    }

    /**
     * 请求返回的处理
     */
    private MyCallback mCallback = new MyCallback() {
        @Override
        public void onSuccess(ResponseBean response, int id) {
            if (response.getCode() == 200) {
                String data = response.getDataInfo().toString();
                LogUtils.e("av=======" + data);
                switch (id) {
                    case 0:
                        setBannerData(data);
                        break;
                    case 1:
                        setNewsData(data);
                        break;
                    case 2:
                        setModuleData(data);
                        break;
                    case 101:
                        VersionBean version = JSON.parseObject(data, VersionBean.class);
                        if (version.getApkversion() > getVersionCode()) {
                            setUpdate(version);
                        }
                        break;
                    default:
                }
            } else {
                showToast(response.getMsg());
            }
        }

        @Override
        public void onError(Throwable e, int id) {
            Log.e("TAG", "id:" + id + "-----------" + e.getMessage());
        }
    };


    /**
     * 设置模块数据
     *
     * @param data
     */
    private List<ModuleBean.ChildBean> list = new ArrayList<>();

    private void setModuleData(String data) {

        List<String> setAuth = SpUtils.getListData("setAuth", String.class);
        LogUtils.e("data=============" + data);

        for (int i = 0; i < setAuth.size(); i++) {
            LogUtils.e("aoao=======" + setAuth.get(i));
        }
        List<ModuleBean> mList = JSON.parseArray(data, ModuleBean.class);
        //List<ModuleItemBean> mItem = mList.get(0).getDeviceList();
       /* for (int i = 0; i < mList.size(); i++) {
            List<ModuleBean.ChildBean> dataList = mList.get(i).getChild();
            String moduleName = mList.get(i).getModuleName();
            for (int j = 0; j < setAuth.size(); j++) {
                LogUtils.e("caac==================="+setAuth.get(i));
                LogUtils.e("ac========="+moduleName);
                if (setAuth.get(j).contains(moduleName)){
                    LogUtils.e("ac=========================================================="+setAuth.get(i));
                    for (ModuleBean.ChildBean bean : dataList) {
                        for (int k = 0; k < setAuth.size(); k++) {
                            if (setAuth.get(k).contains(bean.getModuleName())){
                                list.add(bean);
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }*/
        for (int i = 0; i < mList.size(); i++) {
            List<ModuleBean.ChildBean> dataList = mList.get(i).getChild();
            for (ModuleBean.ChildBean bean : dataList) {
                list.add(bean);
            }

        }


        LogUtils.e("vv====" + list.size());
        for (int i = 0; i < list.size(); i++) {
            LogUtils.e("vv====" + list.get(i).getModuleName());
        }


        /*ArrayList<GridItem> list = new ArrayList<>();
        int[] imags = {R.mipmap.home_equipment_maintain_icon, R.mipmap.home_equipment_report_icon, R.mipmap.home_equipment_ledger_icon, R.mipmap.home_equipment_inspect_icon
                , R.mipmap.home_comprehensive_query_icon, R.mipmap.home_comprehensive_query_icon, R.mipmap.home_comprehensive_query_icon, R.mipmap.home_comprehensive_query_icon};
        String[] titles = {"设备保养", "设备报修", "设备台账", "点/巡检", "生产异常", "iqc检验单", "不合格处理单", "演示"};
        GridItem item_layout;
        for (int i = 0; i < titles.length; i++) {
            item_layout = new GridItem();
            if (i < 7) {
                item_layout.setText(titles[i]);
                item_layout.setDrawableId(imags[i]);
                list.add(item_layout);
            } else if (i == 7) {
                item_layout.setText("更多");
                item_layout.setDrawableId(R.mipmap.home_equipment_more_icon);
                list.add(item_layout);
            }
        }*/
        gridAdapter.setList(list);
    }

    /**
     * 设置新闻数据
     *
     * @param data
     */
    private void setNewsData(String data) {
        NewsListBean newsListBean = JSON.parseObject(data, NewsListBean.class);
        List<NewsListBean.NewsLits> newsList = newsListBean.getNewsList();
        mainAdapter.addData(newsList);
    }


    /**
     * 设置轮播图数据
     *
     * @param data
     */
    private void setBannerData(String data) {
        BannerBean bean = JSON.parseObject(data, BannerBean.class);
        List<BannerBean.BannerItemBean> list = bean.getBannerList();
        for (BannerBean.BannerItemBean itemBean : list) {
            images.add(itemBean.getBannerUrl());
        }
        banner.setImages(images);
        banner.start();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.im_login:
                startActivity(new Intent(MainActivity.this, UserInfoActivity.class));
                break;
            default:
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    /**
     * 该方法用来捕捉手机键盘被按下的事件。
     *
     * @param keyCode  该参数指的是被按下的键的键盘码，手机键盘中每个按钮都会有其对应的键盘码，
     * 在应用程序都是通过键盘码才知道用户按下的是哪个键。
     * @param event    当用户按下按键时，系统会自动将事件封装成KeyEvent对象供应用程序使用。
     * 按键事件KeyEvent 按键事件有多种常量类型，比如 KEYCODE_BACK
     * @return
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //判断用户两次按键的时间差是否在一个预期值之内，是的话直接直接退出，不是的话提示用户再按一次后退键退出。
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
                //当返回true时，表示已经完整地处理了这个事件，并不希望其他的回调方法再次进行处理，而当返回false时，
                // 表示并没有完全处理完该事件，更希望其他回调方法继续对其进行处理，
                return true;
            } else {
                finish(); //结束当前activity
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    private void mVersionUpdate() {
        HttpParams params = new HttpParams();
        params.put("type", "1");
        OkGoUtils.getInstance().post(this, URL.APP_VERSION, params, 101, false, mCallback);
    }

    /**
     * 获取版本号
     *
     * @return
     */
    private int getVersionCode() {
        // 包管理器 可以获取清单文件信息
        PackageManager packageManager = getPackageManager();
        try {
            // 获取包信息
            // 参1 包名 参2 获取额外信息的flag 不需要的话 写0
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private DownloadManager manager;

    private void setUpdate(VersionBean version) {
        /*
         * 整个库允许配置的内容
         * 非必选
         */
        UpdateConfiguration configuration = new UpdateConfiguration()
                //输出错误日志
                .setEnableLog(true)
                //设置自定义的下载
                //.setHttpManager()
                //下载完成自动跳动安装页面
                .setJumpInstallPage(true)
                //设置对话框背景图片 (图片规范参照demo中的示例图)
                //.setDialogImage(R.drawable.ic_dialog)
                //设置按钮的颜色
                //.setDialogButtonColor(Color.parseColor("#E743DA"))
                //设置对话框强制更新时进度条和文字的颜色
                //.setDialogProgressBarColor(Color.parseColor("#E743DA"))
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置是否提示后台下载toast
                .setShowBgdToast(false)
                //设置强制更新
                .setForcedUpgrade(true)
                //设置对话框按钮的点击监听
                .setButtonClickListener(this);

        manager = DownloadManager.getInstance(this);
        manager.setApkName("NaradaApp.apk")
                .setApkUrl(version.getApkUrl())
                .setSmallIcon(R.mipmap.icon)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
                .setApkVersionCode(version.getApkversion())
                .setApkVersionName(version.getApkName())
//                .setApkSize("20.4")
                .setApkDescription(version.getRemark())
//                .setApkMD5("DC501F04BBAA458C9DC33008EFED5E7F")
                .download();
    }

    @Override
    public void onButtonClick(int id) {

    }
}
